package com.ruicar.afs.cloud.afscase.approvetask.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.condition.ApproveTeleCondition;
import com.ruicar.afs.cloud.afscase.approvetask.entity.ApproveTeleRecord;
import com.ruicar.afs.cloud.afscase.approvetask.service.ApproveTeleRecordService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.SoftPhoneVo;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.entity.CaseConfParam;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.service.CaseConfParamService;
import com.ruicar.afs.cloud.common.core.log.annotation.SysLog;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.softphone.dto.ApproveTeleRecordDto;
import com.ruicar.afs.cloud.softphone.softphoneport.SoftPhoneApiFeign;
import com.ruicar.afs.cloud.softphone.softphoneport.TheRecordingApiFeign;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/approveTele")
public class ApproveTeleRecordController {
    private SoftPhoneApiFeign softPhoneService;
    private TheRecordingApiFeign theRecordingApiFeign;
    private CaseConfParamService caseConfParamService;
    private ApproveTeleRecordService teleRecordService;

    @PostMapping("/querySoftPhoneParams")
    @ApiOperation(value = "查询参数")
    public IResponse querySoftPhoneParams(@RequestBody ApproveTeleCondition condition) {
        JSONObject jsonObject = softPhoneService.getSoftPhoneData(condition.getStaffid());
        SoftPhoneVo phoneVo = new SoftPhoneVo();
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            SoftPhoneVo object = JSONObject.parseObject(jsonObject.toJSONString(), SoftPhoneVo.class);
            BeanUtils.copyProperties(object, phoneVo);
        }
        return IResponse.success(phoneVo);
    }

    @PostMapping(value = "/addApproveTele")
    @ApiOperation(value = "新增通话记录")
    @Transactional
    @SysLog("新增通话记录")
    public IResponse<Boolean> addApproveTele(@RequestBody ApproveTeleRecord approveTeleRecord) {
        if (ObjectUtils.isNotEmpty(approveTeleRecord)) {
            approveTeleRecord.setCallTime(new Date());
            String url = this.queryRecordingUrl(approveTeleRecord.getCallId());
            approveTeleRecord.setRecordUrl(url);
            approveTeleRecord.setIsConversion(WhetherEnum.NO.getCode());
            String taskId = teleRecordService.getRecordingId(url);
            if (StringUtils.isNotBlank(taskId)) {
                approveTeleRecord.setTelTaskId(taskId);
                JSONObject jsonObject = teleRecordService.getMessageInfo(taskId);
                if (ObjectUtils.isNotEmpty(jsonObject)) {
                    log.info("语音转文本返回：" + jsonObject.toString());
                    JSONObject json = jsonObject.getJSONObject("payload");
                    if (ObjectUtils.isNotEmpty(json)) {
                        JSONArray array = json.getJSONArray("sentences");
                        if (CollectionUtils.isNotEmpty(array) && ObjectUtils.isNotEmpty(array.getJSONObject(0))) {
                            /**获取语音文本*/
                            String text = array.getJSONObject(0).getString("text");
                            log.info("输出文本:{}", text);
                            approveTeleRecord.setRecordText(text);
                        } else {
                            log.info("响应无文本数据读取:{}", json.toString());
                        }
                    }
                } else {
                    log.info("获取语音文本响应失败:{}", taskId);
                }
            }
        }

        teleRecordService.save(approveTeleRecord);
        return new IResponse<Boolean>().setMsg("新增成功");
    }

    @PostMapping(value = "/voiceHandlerOne")
    @ApiOperation(value = "保存业务数据")
    @Transactional
    @SysLog("保存业务数据")
    public IResponse voiceHandlerOne(@RequestBody ApproveTeleRecordDto recordDto){
            /**返回会话id*/
            String voiceId = softPhoneService.saveVoiceHandlerData(
                    recordDto.getCode(),recordDto.getDirect(),recordDto.getCaller(),recordDto.getCallee(),
                    recordDto.getStaffId(),recordDto.getUintId(),recordDto.getAgentName(),recordDto.getCallId(),
                    recordDto.getApp_no(),recordDto.getCusName(),recordDto.getVoiceId());

            if(StringUtils.isNotBlank(voiceId)){
                return IResponse.success(voiceId);
            }else{
                return IResponse.success(null);
            }

    }
    /**
     * @description: 获取电话录音连接
     * @author jiaqi.guo
     * @created 2020/8/21 17:00
     * @version 1.0
     */
    @SysLog("获取电话录音连接")
    public String queryRecordingUrl(String callId) {
        String resultInfo = "";
        String url = "";
        List<CaseConfParam> confParamList = caseConfParamService.list(Wrappers.<CaseConfParam>query().lambda()
                .eq(CaseConfParam::getParamLogo, "RECORDING")
                .eq(CaseConfParam::getParamStatus, WhetherEnum.YES.getCode()));
        if (CollectionUtils.isNotEmpty(confParamList)) {
            /**注意维护数据的顺序*/
            resultInfo = theRecordingApiFeign.getRecordingData(
                    callId
                    ,confParamList.get(0).getParamValue()
                    ,confParamList.get(1).getParamValue()
                    ,confParamList.get(2).getParamValue());
        } else {
            log.info("获取录音URl请求参数不全");
        }
        /**获取url地址*/
        if (StringUtils.isNotBlank(resultInfo)) {
            JSONObject object=JSONObject.parseObject(resultInfo);
            if (object.get("result").equals("ok")) {
                JSONArray array = object.getJSONArray("files");
                if (CollectionUtils.isNotEmpty(array)) {
                    url = array.getJSONObject(0).getString("url");
                }
            }
        }
        return url;
    }
}